<template>
  <div class="main-content">
    <AsyncSearchTable :columns="allColumns"
                      :query-params="queryParams"
                      :search-items="searchItems"
                      :fetch-data="fetchMenus"
                      :show-pagination="false"
                      :is-tree-table="true"
                      :tree-config="treeConfig">
      <template #icon="{ row }">
        <el-icon v-if="row.icon">
          <component :is="iconMap[row.icon]"/>
        </el-icon>
        <span v-else>-</span>
      </template>
      <template #toolbar>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </template>
      <template #action-column>
        <el-button type="primary" link :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" link :icon="Edit" @click="handleEdit">修改</el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete">删除</el-button>
      </template>
    </AsyncSearchTable>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        append-to-body
    >
      <el-form
          ref="menuFormRef"
          :model="menuForm"
          :rules="menuRules"
          label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
              v-model="menuForm.parentId"
              :data="menuOptions"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              value-key="id"
              placeholder="选择上级菜单"
              check-strictly
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type" @change="handleTypeChange">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称"/>
        </el-form-item>
        <el-form-item label="路由地址" prop="path" v-if="menuForm.type !== 'F'">
          <el-input v-model="menuForm.path" placeholder="请输入路由地址"/>
        </el-form-item>
        <el-form-item label="权限标识" prop="permission" v-if="menuForm.type !== 'M'">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识"/>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" controls-position="right"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AsyncSearchTable from '@/components/AsyncSearchTable/index.vue'
import * as http from "@/api/http.ts"
import {Delete, Edit, Plus} from "@element-plus/icons-vue"
import type {MenuItem} from '@/config/menu'
import {iconMap} from '@/config/menu'
import type {SearchItem} from "@/types/search.ts"

// 扩展MenuItem类型
interface MenuItemWithExtra extends MenuItem {
  parentId?: string
  type?: 'M' | 'C' | 'F'
  sort?: number
}

const queryParams = ref({
  name: undefined,
  path: undefined,
  status: undefined,
  createdTime: undefined
})

// 表格多选相关
const selectedRows = ref<MenuItemWithExtra[]>([])
// 所有可用的列配置
const allColumns = [
  {prop: 'name', label: '菜单名称', width: '180'},
  {prop: 'icon', label: '图标', width: '100'},
  {prop: 'path', label: '路由地址', width: '180'},
  {prop: 'permission', label: '权限标识', width: '180'},
  {prop: 'sort', label: '排序', width: '80'},
  {prop: 'createdTime', label: '创建时间', width: '160'},
  {prop: 'createdBy', label: '创建者', width: '100'},
  {prop: 'updatedTime', label: '更新时间', width: '160'},
  {prop: 'updatedBy', label: '更新者', width: '100'}
]

// 菜单树选项
const menuOptions = ref<MenuItemWithExtra[]>([])
// 树形表格配置
const treeConfig = {
  rowKey: 'id',
  treeProps: {
    children: 'children',
    hasChildren: 'hasChildren'
  }
}
// 是否显示弹出层
const dialogVisible = ref(false)
// 弹出层标题
const dialogTitle = ref('')
// 表单对象
const menuForm = ref({
  id: '',
  parentId: '',
  name: '',
  icon: '',
  path: '',
  permission: '',
  type: 'M',
  sort: 0,
  createdTime: '',
  createdBy: '',
  updatedTime: '',
  updatedBy: ''
})
// 表单校验规则
const menuRules = {
  name: [
    {required: true, message: '菜单名称不能为空', trigger: 'blur'}
  ],
  path: [
    {required: true, message: '路由地址不能为空', trigger: 'blur'}
  ]
}

// 获取菜单列表
const fetchMenus = async () => {
  try {
    const response = await http.get('/api/menus')
    menuOptions.value = [{id: '0', name: '主目录', children: response.data.list}]
    return response.data
  } catch (error) {
    console.error('获取菜单列表失败', error)
    ElMessage.error('获取菜单列表失败')
    return []
  }
}

// 状态选项
const statusOptions = [
  {label: '全部', value: ''},
  {label: '正常', value: '0'},
  {label: '停用', value: '1'}
]

// 搜索项配置
const searchItems: SearchItem[] = [
  {
    field: 'name',
    label: '菜单名称',
    type: 'input',
    placeholder: '请输入菜单名称'
  },
  {
    field: 'path',
    label: '路由地址',
    type: 'input',
    placeholder: '请输入路由地址'
  },
  {
    field: 'status',
    label: '状态',
    type: 'select',
    options: statusOptions
  },
  {
    field: 'createdTime',
    label: '创建时间',
    type: 'date'
  }
]

// 新增按钮操作
const handleAdd = (row?: MenuItemWithExtra) => {
  dialogTitle.value = '添加菜单'
  const now = new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().split(' ')[0]

  // 生成默认的排序值 - 默认为10，如果有父菜单则基于其他子菜单的数量递增
  let defaultSort = 10
  if (row?.id) {
    const parentMenu = menuOptions.value[0]?.children?.find(item => item.id === row.id)
    if (parentMenu && parentMenu.children) {
      defaultSort = (parentMenu.children.length + 1) * 10
    }
  }

  // 默认菜单类型
  const defaultType = row?.id ? 'C' as const : 'M' as const

  // 生成默认的权限字符 - 基于菜单类型
  let defaultPermission = 'system:menu:list'
  if (defaultType === 'C') {
    defaultPermission = 'system:menu:view'
  }

  menuForm.value = {
    id: '',
    parentId: row?.id || '0',
    name: '',
    icon: '',
    path: '',
    permission: defaultPermission,
    type: defaultType,
    sort: defaultSort,
    createdTime: now,
    createdBy: 'admin',
    updatedTime: now,
    updatedBy: 'admin'
  }
  dialogVisible.value = true
}

// 修改按钮操作
const handleEdit = (row: MenuItemWithExtra) => {
  dialogTitle.value = '修改菜单'
  const now = new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().split(' ')[0]

  menuForm.value = {
    id: row.id,
    parentId: row.parentId || '0',
    name: row.name,
    icon: row.icon || '',
    path: row.path || '',
    permission: row.permission || '',
    type: row.type || 'M',
    sort: row.sort || 0,
    createdTime: row.createdTime || '',
    createdBy: row.createdBy || '',
    updatedTime: now,
    updatedBy: 'admin'
  }
  dialogVisible.value = true
}

// 删除按钮操作
const handleDelete = (row: MenuItemWithExtra) => {
  ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除接口
    console.log('删除菜单', row.id)
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除按钮操作
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用批量删除接口
    console.log('批量删除菜单', selectedRows.value.map(row => row.id))
  }).catch(() => {
    // 取消批量删除
  })
}

// 提交表单
const submitForm = () => {
  // 表单校验
  ElMessageBox.confirm('确定要提交表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用提交接口
    console.log('提交表单', menuForm.value)
  }).catch(() => {
    // 取消提交
  })
}

// 取消表单
const cancel = () => {
  dialogVisible.value = false
}

// 菜单类型变更事件
const handleTypeChange = () => {
  // 根据菜单类型自动设置权限字符
  if (menuForm.value.type === 'C') {
    menuForm.value.permission = 'system:menu:view'
  } else {
    menuForm.value.permission = 'system:menu:list'
  }
}
</script>

<style scoped>
/* 添加自定义样式 */
</style>